import 'package:base_flutter/base_flutter.dart' as b;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_elder/models/follow_bean.entity.dart';
import 'package:ls_work/a_elder/models/upload_entity.dart';
import 'package:ls_work/config/permission_center_config.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/util/toast.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'dart:io';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:dio/dio.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:ls_work/util/utils.dart';
import 'package:ls_work/widgets/gallery_photo_browser.dart';
import 'package:oktoast/oktoast.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../login/page/user_manager.dart';
import '../../util/ext_utils.dart';
import '../../util/flat_button.dart';

class MedicalPhotoPage extends StatefulWidget {
  final ReportInfo? info;
  MedicalPhotoPage({required this.info});
  @override
  _MedicalPhotoPageState createState() => _MedicalPhotoPageState();
}

class _MedicalPhotoPageState extends State<MedicalPhotoPage> {
  File? image;
  Upload? upload;
  List<Upload> dataList = [];
  final List<int> imgUrlList = [];

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectList();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('照片上传'),
        elevation: 0.5,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
              child: GridView.builder(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, //每行三列
              childAspectRatio: 1.0, //显示区域宽高相等
              mainAxisSpacing: 10,
              crossAxisSpacing: 10,
            ),
            itemCount: dataList.length,
            itemBuilder: (context, index) {
              return GestureDetector(
                onLongPress: () {
                  _showCupertinoAlertDialog(context, index);
                },
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => GalleryPhotoViewWrapper(
                        galleryItems: imgUrlList,
                        backgroundDecoration: const BoxDecoration(
                          color: Colors.black,
                        ),
                        initialIndex: index,
                      ),
                    ),
                  );
                },
                child: CachedNetworkImage(
                  height: 100,
                  fit: BoxFit.cover,
                  httpHeaders: {"Cookie":UserManager.cookieStr},
                  imageUrl: HttpApi.imageDownLoadUrl +
                      '${dataList[index].fileId}',
                  placeholder: (context, url) => new ProgressView(),
                  errorWidget: (context, url, error) => new Icon(Icons.error),
                ),
              );
            },
          ) //NetworkImage(''),
              ),
          Container(
            padding: EdgeInsets.only(left: 20, right: 20, bottom: 40),
            height: 90,
            width: double.infinity,
            child: FlatsButton(
              child: Text("上传",
                  style: TextStyle(fontSize: 18, color: Colors.white)),
              color: Colours.app_main,
              onPressed: _pickImageFromSource,
            ),
          ),
        ],
      ),
    );
  }

  ///获取照片列表
  _fectList() {
    var map = {
      'customerId': widget.info?.customerId,
      'examinationRecordDetailId': widget.info?.id,
      'examinationRecordId': widget.info?.examinationRecordId,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post("${HttpApi.detailItemFile}?${requestParams(map)}")
        .then((r) {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            PhotoEntity model = PhotoEntity.fromJson(map['data']);
            setState(() {
              dataList = model.rows??[];
              for (Upload da in model.rows??[]) {
                imgUrlList.add(da.fileId!);
              }
            });
          } else {
            Toast.show(map["msg"]);
          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  Future<void> submitToHealthCase() async {
    var url = "${HttpApi.baseUrl}customerExaminationRecord/reviewSubmit";
    var map = {
      "customerId": widget.info?.customerId,
      "examinationRecordId": widget.info?.examinationRecordId,
    };

    var submitMap = {
      "jsonStr":jsonEncode(map),
      "listDetail": jsonEncode([
        {
          "id":widget.info?.id,
          "examinationStatus":"3",
          "reviewRemark" :null
        }
      ])
    };
    try{
      var data = await b.HttpGo.instance.postData(url,data: submitMap,options: b.Options(contentType: b.Headers.formUrlEncodedContentType));
      if("0"==data['code']){

      }else{
        showToast(data['msg']);
      }
    }catch(e){
      Toast.show(e.toNetError());
    }
  }

  _agencyList() {
    var map = {
      'customerId': widget.info?.customerId,
      'examinationRecordDetailId': widget.info?.id,
      'examinationRecordId': widget.info?.examinationRecordId,
      'fileId': upload?.id,
      'filePath': upload?.path,
      'fileName': upload?.fileName,
    };
    HttpUtil.instance
        .getDio()
        .post("${HttpApi.uploadExamination}",data: map.toJsonMapStr())
        .then((r) async {
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          await submitToHealthCase();
          _fectList();
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///上传
  _upLoadImage(File image) async {
    String path = image.path;
    print(path);
    var name = path.substring(path.lastIndexOf("/") + 1, path.length);
    var type = path.split(".").last;
    FormData formData = new FormData.fromMap({
      'fileType': type,
      'fileToUpload': await MultipartFile.fromFile(path, filename: name),
    });
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.upload, data: formData).then((r) async {
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            Upload model = Upload.fromJson(map['data']);
            setState(() {
              upload = model;
            });
            await _agencyList();
          } else {
            Toast.show(map["msg"]);

          }
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///选择图片方式
  _pickImageFromSource() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机"),
                onTap: () async {
                  Navigator.pop(context);
                  Permission.camera.checkRequestPermission(
                    context,
                    onSuccess: () async {
                      var imageFile =
                      await ImagePicker().pickImage(source: ImageSource.camera);
                      if(imageFile!=null){
                        setState(() {
                          image = File(imageFile.path);
                          // makeLogoString(_image.path);

                        });
                        _upLoadImage(File(imageFile.path));
                      }
                    },
                    msg: "使用扫一扫扫描长者码、访客码等二维码以及拍照上传工作照片、长者头像、健康档案时，需要申请您的相机权限",
                  );

                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("相册"),
                onTap: () async {
                  Navigator.pop(context);
                  var isAndroid13 = await isAndroid13OrAbove();
                  if(isAndroid13){
                    Permission.photos.checkRequestPermission(
                      context,
                      onSuccess: () async {
                        var imageFile =
                        await ImagePicker().pickImage(source: ImageSource.gallery);
                        if(imageFile!=null){
                          // setState(() {
                          //   image = File(imageFile.path);
                          //   // makeLogoString(_image.path);
                          //
                          // });
                          _upLoadImage(File(imageFile.path));
                        }
                      },
                      msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
                    );
                  }else{
                    Permission.storage.checkRequestPermission(
                      context,
                      onSuccess: () async {
                        var imageFile =
                        await ImagePicker().pickImage(source: ImageSource.gallery);
                        if(imageFile!=null){
                          // setState(() {
                          //   image = File(imageFile.path);
                          //   // makeLogoString(_image.path);
                          //
                          // });
                          _upLoadImage(File(imageFile.path));
                        }
                      },
                      msg: "从相册选取上传工作照片、长者头像、健康档案时，需要申请您的相册权限",
                    );
                  }

                },
              ),
            ],
          );
        });
  }

  void _showCupertinoAlertDialog(BuildContext cxt, int index) {
    showCupertinoDialog<int>(
        context: cxt,
        builder: (cxt) {
          return CupertinoAlertDialog(
            title: Text('提示'),
            content: Text('是否要删除？'),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("确定"),
                onPressed: () {
                  _deleteContractFavor(index);
                  Navigator.pop(context);
                },
              ),
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ],
          );
        });
  }

  _deleteContractFavor(int index) {
    var map = {'id': dataList[index].id};
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post(HttpApi.deleteExamination, data: map)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          Toast.show(map["msg"]);
          _fectList();
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      Toast.show(getErrorMessage(e));
    });
  }
}
